package com.example.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.example.annotation.OperLog;
import com.example.model.TestUser;
//import com.liang.HelloService;
import com.example.service.IMsgRemindService;
import com.example.service.IOAWorkflowService;
import com.example.service.ISMSService;
 import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.util.ClassLoaderUtil.getClassLoader;

/**
 * @author leiliang
 * @version 1.0
 * @Description
 * @date 2022/8/16 17:05
 */
@RestController
@RequestMapping("/demo")
@Slf4j
public class DemoController {

    @Autowired
    ISMSService ismsService;
    @Autowired
    IOAWorkflowService ioaWorkflowService;
    @Autowired
    IMsgRemindService msgRemindService;
    //@Autowired
    //HelloService helloService;
    @Value("${javaboy.name}")
    private String name;

    @GetMapping("/hello")
    public String getHello() {
        return "HELLO";
    }

    @GetMapping("/name")
    public String getName() {
        String result = "";//helloService.sayHello();
        return result;
    }


    /*public static void main(String[] args) {
        String result =  "[{\"name\":\"张三\",\"age\":\"12\"},{\"name\":\"李四\",\"age\":\"88\"}]";
        JSONArray jsonArray = JSON.parseArray(result);
         System.out.printf("jsonArray" +jsonArray);
        *//* HashMap<String, String> resultMap = new HashMap<>();
        String result = "{\n" +
                "  \"code\" : 0,\n" +
                "  \"data\" : {\n" +
                "    \"workitems\" : [ {\n" +
                "      \"nodeName\" : \"节点姓名\",\n" +
                "      \"userLoginName\" : \"loginName\",\n" +
                "      \"id\" : \"6063271658185834554\",\n" +
                "      \"userName\" : \"用户姓名\",\n" +
                "      \"nodeId\" : \"15940211100644\",\n" +
                "      \"userId\" : \"5647565013925644425\"\n" +
                "    } ],\n" +
                "    \"app_bussiness_data\" : \"{\\\"affairId\\\":\\\"-7826004588359563757\\\",\\\"summaryId\\\":\\\"2076716881761815485\\\"}\",\n" +
                "    \"processId\" : \"5724125432261003059\",\n" +
                "    \"subject\" : \"aaa1\",\n" +
                "    \"errorMsg\" : \"\"\n" +
                "  },\n" +
                "  \"message\" : \"\"\n" +
                "}";
         com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
        com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("data");
        if (data != null) {
            String processId = data.getString("processId");
            log.info("【发起流程审批， 返回流程ID={}】", processId);
            resultMap.put("processId",processId);
            JSONObject appBussinessData = data.getJSONObject("app_bussiness_data");
            if (appBussinessData != null){
                String summaryId = appBussinessData.getString("summaryId");
                resultMap.put("summaryId",summaryId);
            }
        }
        System.out.printf("resultMap=====" + resultMap );*//*
    }
*/
    @PostMapping("/send")
    public int send(String phone, String message) {
        int result = ismsService.sendMessage(phone, message);
        return result;
    }

    @GetMapping("/checkFlowStatus")
    public int checkFlowStatus(String workflowCode) {
        int result = ioaWorkflowService.checkFlowStatus(workflowCode);
        return result;
    }

    @PostMapping("/sendMsgRemind")
    public int sendMsgRemind(@RequestParam("userId")String userId,
                             @RequestParam("title")String title,
                                @RequestParam("content") String content) {
        int result = msgRemindService.sendMsgRemind(userId, title,content);
        return result;
    }


    @GetMapping("/getToke")
    public String getToke(String userName, String password) {
        String result = ioaWorkflowService.getToke(userName,password);
        return result;
    }

    @GetMapping("/test1")
    @OperLog(businessModul="模板报告",operModul="业务报告预览下载",operMessage="业务报告预览下载")
    public String test1(String userName) {
        int i = 1/0;
        return "test1";
    }

    @PostMapping("/upload")
    public List<HashMap<String, Object>> uploadFiles( List<MultipartFile> multipartFiles) {
          //String resultJson =  "[{\"fileName\":\"菜单初始化.sql\",\"filePath\":\"\u202AE:\\swhy-work\\文档资料\\菜单初始化.sql\"}]";
        String  resultJson  = "[{\"fileName\":\"play.txt\",\"filePath\":\"E:/study-workspace/springboot-mp/src/main/resources/play.txt\"},{\"fileName\":\"b.txt\",\"filePath\":\"E:/study-workspace/springboot-mp/src/main/resources/b.txt\"}]";
        JSONArray jsonArray = JSONObject.parseArray(resultJson);
         List<MultipartFile> filess = new ArrayList<>();
        List<FileTest> fileLists = new ArrayList<>();
         for (int i = 0; i < jsonArray.size(); i++) {
             FileTest fileObj = new FileTest();
            JSONObject o = jsonArray.getJSONObject(i);
             fileObj.setFileName(o.getString("fileName"));
             fileObj.setFilePath(o.getString("filePath"));
             //MultipartFile multipartFile = createFileItem(o.getString("filePath"), o.getString("fileName"));
             MultipartFile multipartFile = createFileItem(o.getString("filePath"), o.getString("fileName"));

             fileLists.add(fileObj);
             filess.add(multipartFile);
        }
          List<HashMap<String, Object>> result = ioaWorkflowService.uploadFiles(filess);
        return result;
    }


    /**
     * @description:  根据文件路径，获取MultipartFile对象
     * @author: nisan
     * @date: 2022/1/18 13:08
     * @param
     * @return org.springframework.web.multipart.MultipartFile
     */
/*    public static MultipartFile createMfileByPath(String path) {
        MultipartFile mFile = null;
        try {
            File file = new File(path);
            FileInputStream fileInputStream = new FileInputStream(file);

            String fileName = file.getName();
            //fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
            mFile =  new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (Exception e) {
            log.error("封装文件出现错误：{}", e);
            //e.printStackTrace();
        }
        return mFile;
    }*/

    public static MultipartFile getMultipartFile(String filePaath) {
        File file = new File(filePaath);
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int)file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile cMultiFile =new CommonsMultipartFile((FileItem) item);
        return cMultiFile;
    }

    public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int)file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  new CommonsMultipartFile((FileItem) item);

     }


    public static void main(String[] args) {
        /*FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("F:\\poi笔记.docx");
            XWPFDocument xwpfDocument = null;
                xwpfDocument = new XWPFDocument(fileInputStream);
            PdfOptions pdfOptions = PdfOptions.create();
            FileOutputStream fileOutputStream = new FileOutputStream("F:\\poi笔记.pdf");
                PdfConverter.getInstance().convert(xwpfDocument,fileOutputStream,pdfOptions);
            System.out.printf("【输出流】====" + fileOutputStream);
                fileInputStream.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        String aa ="/opt/数据.docx";
        if ( aa.contains(".docx")){
            String pdf = aa.replace(".docx", ".pdf");
            System.out.printf("pdf" + pdf);
            System.out.printf("aa" + aa);
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String filepath = "F:\\poi笔记.docx";
            String outpath = "F:\\poi笔记.pdf";
            inputStream = new FileInputStream(filepath);
            outputStream = new FileOutputStream(outpath);
            //wordToPdf(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }








    public static MultipartFile createFileItem(String filePath, String fileName){
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(newfile);
             OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
         MultipartFile cMultiFile = new CommonsMultipartFile(item);
        return cMultiFile;
    }



    @PostMapping("/startFlow")
     public String startFlow(@RequestParam Map<String, Object> params,List<MultipartFile> files){
        String result = ioaWorkflowService.startFlow(params,files);
        return result;
    }


    /**
     * word转 pdf
     * @param response
     * @throws Exception
     */
    @GetMapping("/wordToPdf")
    public void wordToPdf(HttpServletResponse response) throws Exception {
        String urlStr = "E:/study-workspace/springboot-mp/src/main/resources/中原证券二期架构设计说明书v1.0.docx";
        String newPdfPath = "";

        File file = new File(urlStr);
        String fileName = file.getName();
        log.info("预览系统报告文件名称为：" + fileName);
        if (urlStr.contains(".docx")) {
            newPdfPath = urlStr.replace(".docx", ".pdf");
        }
        log.info("【要预览的系统报告PDF文件路径为 ={}】", newPdfPath);
        InputStream inputStream = null;
        OutputStream out = null;
         /*inputStream = new FileInputStream(urlStr);
        out = new FileOutputStream(newPdfPath);

       XWPFDocument docxDocument = new XWPFDocument(inputStream);
        PdfOptions pdfOptions = PdfOptions.create();
        PdfConverter.getInstance().convert(docxDocument, out, pdfOptions);*/
        //doc2pdf(urlStr,newPdfPath);
        //docx4jWordToPdf(urlStr,newPdfPath);
        InputStream docxInputStream = new FileInputStream(urlStr);
          out = new FileOutputStream(newPdfPath);
        IConverter converter = LocalConverter.builder().build();
        converter.convert(docxInputStream).as(DocumentType.DOCX).to(out).as(DocumentType.PDF).execute();
        response.setContentType("application/pdf");
        try {
            File pdfFile = new File(newPdfPath);
            if (pdfFile.exists()) {
                FileInputStream in = new FileInputStream(pdfFile);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[1024 * 5];
                int n;
                while ((n = in.read(b)) != -1) {
                    outputStream.write(b, 0, n);
                }
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过docx4j 实现word转pdf
     *
     * @param sourcePath 源文件地址 如 /root/example.doc
     * @param targetPath 目标文件地址 如 /root/example.pdf
     */
    public static void docx4jWordToPdf(String sourcePath, String targetPath) {
        try {
            WordprocessingMLPackage pkg = Docx4J.load(new File(sourcePath));
            Docx4J.toPDF(pkg, new FileOutputStream(targetPath));
        } catch (Exception e) {
            log.error("[docx4j] word转pdf失败:{}", e.toString());
        }
    }

    @RequestMapping("/toPdf")
    private String wordToPdf() {
        File inputWord = new File("测试文档.doc");
        File outputFile = new File("测试文档.pdf");
        try {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();

            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "转换成功~";
    }



/*
Word2PdfAsposeUtil.doc2pdf(docPath,pdfPath);
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Test.class.getClassLoader().getResourceAsStream("\\license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功，共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
*/

}
